package propertymanager.rap;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.rap.rwt.RWT;
import org.eclipse.rap.rwt.service.ServiceHandler;


public class DownloadServiceHandler implements IDownloadServiceHandler, ServiceHandler {

	private String filePath = "C:\\Temp\\";
	
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		  // Which file to download?
	    String fileName = (String) request.getParameter( "filename" );
	    if ( fileName == null ){
	    	fileName = (String) request.getAttribute( "filename" );
	    }
	    // Get the file content
	    
	    Path path = Paths.get( filePath + fileName );
	    byte[] download = Files.readAllBytes( path  );
	    // Send the file in the response    
	    response.setContentType( "application/octet-stream" );
	    response.setContentLength( download.length );
	    String contentDisposition = "attachment; filename=\"" + fileName + "\"";
	    response.setHeader( "Content-Disposition", contentDisposition );
	    response.getOutputStream().write( download );
		
	}
	
	public String createDownloadUrl( String filename ) {
	  StringBuilder url = new StringBuilder();
	  url.append( RWT.getServiceManager().getServiceHandlerUrl( "downloadServiceHandler" ) );
	  url.append( '&' ).append( "filename" ).append( '=' ).append( filename );
	  return url.toString();
	}
	
}
